package novel.spider.util;

import novel.spider.NovelSiteEnum;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by Kau on 2016/10/30.
 */
public final class NovelSpiderUtil {
    private static final Map<NovelSiteEnum,Map<String, String>> CONTEXT_MAP = new HashMap<>();
    //即运行
    static {
        init();
    }
    //禁止实例化
    private NovelSpiderUtil(){}

    private static void init(){
        SAXReader reader = new SAXReader();
        try {
            //通过配置文件读取
            Document doc = reader.read(new File("src/conf/Spider-Rules.xml"));
            //获取根节点
            Element root = doc.getRootElement();
            List<Element> sites = root.elements("site");
            for (Element site : sites){
                List<Element> subs = site.elements();
                Map<String, String> subMap = new HashMap<>();
                for (Element sub : subs){
                    String name = sub.getName();
                    String text = sub.getTextTrim();
                    subMap.put(name, text);
                }
                CONTEXT_MAP.put(NovelSiteEnum.GetEnumByUrl(subMap.get("url")),subMap);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 通过配置文件获取对应网站的解析规则
     * @param novelSiteEnum
     * @return
     */
    public static Map<String, String> getContext(NovelSiteEnum novelSiteEnum){
        return CONTEXT_MAP.get(novelSiteEnum);
    }

    /**
     * 合并文件，规则：按文件名分割排序
     * @param path 基础合并目录
     * @param mergeToFile 被合并的文本文件，可以为空
     */
    public static void multiFileMerge(String path, String mergeToFile, boolean deleteThisFile){
        mergeToFile = mergeToFile == null ? path + "/merge.txt" : mergeToFile;
        File[] files = new File(path).listFiles(new FilenameFilter() {
            @Override
            public boolean accept(File dir, String name) {
                return name.endsWith(".txt");
            }
        });
        Arrays.sort(files, new Comparator<File>() {
            @Override
            public int compare(File o1, File o2) {
                int o1Index = Integer.parseInt(o1.getName().split("\\-")[0]);
                int o2Index = Integer.parseInt(o2.getName().split("\\-")[0]);
                if (o1Index > o2Index) {
                    return 1;
                } else if (o1Index == o2Index) {
                    return 0;
                } else {
                    return -1;
                }
            }
        });
        PrintWriter out = null;
        try {
            out = new PrintWriter(new File(mergeToFile), "UTF-8");
            for (File file : files){
                BufferedReader buffer = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));
                String line = null;
                while ((line = buffer.readLine()) != null){
                    out.println(line);
                }
                buffer.close();
                if (deleteThisFile){
                    file.delete();
                }
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            out.close();
        }
    }

    /**
     * 获取书籍状态
     * @param status
     * @return
     */
    public static int getNovelStatus(String status) {
        if (status.contains("连载")) {
            return 1;
        } else if (status.contains("完结") || status.contains("完成")) {
            return 2;
        } else {
            throw new RuntimeException("不支持的书籍状态" + status);
        }
    }

    /**
     * 格式化日期字符串为日期对象
     * @param dateStr
     * @param pattern
     * @return
     * @throws ParseException
     */
    public static Date getDate(String dateStr, String pattern) throws ParseException {
        if ("MM-dd".equals(pattern)){
            pattern = "yyyy-MM-dd";
            dateStr = getDateFiedld(Calendar.YEAR) + "-" + dateStr;
        }
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        Date date = sdf.parse(dateStr);
        return date;
    }

    public static String getDateFiedld(int Fiedld){
        Calendar cal = new GregorianCalendar();
        return cal.get(Fiedld) + "";
    }
}
